package com.oxy.nativegles;

import android.opengl.GLSurfaceView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MainActivity extends AppCompatActivity {

    //是否继续渲染
    private boolean isPlayer = true;

    private GLSurfaceView glSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        glSurfaceView = new GLSurfaceView(getApplication());

        setContentView(glSurfaceView);

        glSurfaceView.setEGLConfigChooser(8, 8, 8, 0, 16, 0);

        glSurfaceView.setEGLContextClientVersion(3);

        glSurfaceView.setRenderer(new GLSurfaceView.Renderer() {
            @Override
            public void onSurfaceCreated(GL10 gl, EGLConfig config) {

                initShader();

                initData();

                new Thread(() -> {

                    while (isPlayer || glSurfaceView != null) {

                        glSurfaceView.requestRender();

                    }

                }).start();

            }

            @Override
            public void onSurfaceChanged(GL10 gl, int width, int height) {

                rsize(width, height);

            }

            @Override
            public void onDrawFrame(GL10 gl) {

                if (render() != 0) isPlayer = false;

            }
        });

        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);


    }



    @Override
    public void onResume() {
        super.onResume();

        glSurfaceView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();

        glSurfaceView.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        destroy();

        isPlayer = false;

        glSurfaceView = null;
    }

    //Native render function
    protected final native int render();

    protected final native void initData();

    protected final native void rsize(int width, int height);

    protected final native void initShader();

    protected final native void destroy();

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}
